﻿using System;
using System.Collections.Generic;
using System.Text;
using ToolManager.IService;
using Azure.Storage.Blobs;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using ToolManager.Entities;
using ToolManager.Common;
using System.Threading;

namespace ToolManager.Service
{
    public class StorageService : IStorageService
    {
        public readonly ConnectionStrings _connectionStrings;
        public StorageService(ConnectionStrings connectionStrings)
        {
            _connectionStrings = connectionStrings;
        }
        public async Task<CloudTable> GetCloudTable(string tableName)
        {
            var cloudTable = CloudStorageAccount.Parse(_connectionStrings.storageConnectionString).CreateCloudTableClient().GetTableReference(tableName);
            await cloudTable.CreateIfNotExistsAsync();
            return cloudTable;
        }

        public async Task<TableBatchResult> InsertBatchData(TableBatchOperation batch, string tableName)
        {
            var result = new TableBatchResult();

            var cloudTable = await GetCloudTable(tableName);
            result = await cloudTable.ExecuteBatchAsync(batch);
            return result;
        }
        public async Task<List<T>> GetBusData<T>(string tableName,TableQuery<T> queryBody = null, CancellationToken ct = default(CancellationToken)) where T : ITableEntity, new()
        {
            var cloudTable = await GetCloudTable(tableName);
            TableContinuationToken token = null;
            var result = new List<T>();
            do
            {
                TableQuerySegment<T> seg = await cloudTable.ExecuteQuerySegmentedAsync(queryBody, token);
                token = seg.ContinuationToken;
                result.AddRange(seg);
            }
            while (token != null & ct.IsCancellationRequested);
            return result;
        }

        public async Task<bool> DeleteTableAsync(string tableName)
        {
            var cloudTable = CloudStorageAccount.Parse(_connectionStrings.storageConnectionString).CreateCloudTableClient().GetTableReference(tableName);
            return await cloudTable.DeleteIfExistsAsync();
        }


    }
}
